package com.aptech.fpt.c0810g.newspj.dataaccess.share;

import com.sun.faces.util.CollectionsUtils.ConstMap;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author zang
 */
public class InvokeSelectQuery {

    /**
     * @author AnhGT
     * @param pColumns Cac cot muon rtuy van 
     * @param pConditions Cac dieu kien (Khong co thi de null)
     * @param pTableName Ten bang muon truy van
     * @return DAnh sach cac ban ghi 
     **/
    public ArrayList<HashMap<String, Object>> getList(ArrayList<String> pColumns, String pTableName, ArrayList<String> pConditions) {

        //Danh sach ban ghi
        ArrayList<HashMap<String, Object>> records = new ArrayList<HashMap<String, Object>>();

        Connection con = null;
        Statement stmt = null;
        //Tao cac cot muon truy van
        String columns = process(pColumns, ",");
        String strQuery = "SELECT " + columns + " FROM " + pTableName;
        //Tao cac dieu kien
        if (pConditions.size() > 0) {
            String codition = process(pConditions, " AND ");
            strQuery +=" WHERE "+ codition;
        }
        try {
            //lay ve chuoi connection
            con = new GetConnection().GetObj();
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(strQuery);

            while (rs.next()) {
                //Ham luu danh thuc the item
                HashMap<String, Object> item = new HashMap<String, Object>();
                for (Object str : pColumns) {
                    item.put(str.toString(), rs.getObject(str.toString()));
                }
                records.add(item);
            }
        } catch (Exception e) {
        } finally {
            try {
                con.close();
                stmt.close();
            } catch (SQLException ex) {
            }
        }
        return records;
    }

    /**
     * @author AnhGT
     * @param pColumns Danh sach cac cot muon truy van
     * @return Chuoi cac cot muon truy van
     **/
    public String process(ArrayList<String> pColumns, String charactor) {
        String columns = "";
        for (int i = 0; i < pColumns.size(); i++) {
            //them , vao sau moi column
            if (i != 0) {
                columns += charactor;
            }
            //them cac column
            columns += pColumns.get(i);
        }
        return columns;
    }
}
